package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chinamcloud.audioserver.APSHelper;
import com.chinamcloud.audioserver.MusicEntity;
import com.chinamcloud.audioserver.TaskAudioConfig;
import com.chinamcloud.collect.AcquisitionManager;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.DateParse;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.cloud.ijkplayersdk.auth.AuthMode;
import com.mediacloud.app.cloud.ijkplayersdk.auth.URLAuth;
import com.mediacloud.app.model.adaptor.BaseAdaptor;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.LiveProgramListReciver;
import com.mediacloud.app.model.news.LiveProgramListReciver.ProgramWeekItem;
import com.mediacloud.app.model.news.ProgramListItem;
import com.mediacloud.app.model.news.ProgramListItem.GuideItemState;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.broadcast.AudioLiveBroadcast;
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast;
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast.LiveReplayHandle;
import com.mediacloud.app.newsmodule.fragment.audio.live.AudioLiveProgramTable;

import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.LiveMediaPlayBackInvoker;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.VideoLiveProgramListInvoker;
import com.mediacloud.app.newsmodule.utils.support.SupportKit;
import com.mediacloud.app.newsmodule.view.AudioBottomPopWin;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.shared.AppSharePreference;

import com.mediacloud.app.user.model.UserInfo;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.qcloud.tim.uikit.component.AudioPlayer;
import com.tencent.qcloud.tim.uikit.modules.chat.ChatLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.input.InputLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.inputmore.InputMoreFragment;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 音频直播类
 *
 * @author x
 */
public class AudioLiveDetailActivity extends BaseAudioActivity implements LiveReplayHandle, OnItemClickListener, LiveReplayBroadcast.ToggleHandle {
    /**
     * 节目单数据
     */
    List<ProgramWeekItem> programListItems;
    /**
     * 取节目单用的
     */
    VideoLiveProgramListInvoker liveProgramListInvoker;
    /**
     * 节目单
     */
    AudioLiveProgramTable audioLiveProgramTable;
    /**
     * 节目单的view
     */
    View programView;
    private Animation showAnimation;
    protected LiveReplayBroadcast liveReplayBroadcast;
    private List<String> bitRateUrls = new ArrayList<>();
    private List<String> bitRateTitles = new ArrayList<String>();
    NewsDetailInvoker newsDetailInvoker;
    AudioDetailCallBack audioDetailCallBack;
    ProgramListCallBack programListCallBack;
    AudioLiveBroadcast broadcast;
    int bitRateIndex = 0;
    List<String> streamLabelList = new ArrayList<String>();
    AuidoStreamLineAdaptor streamLabelAdaptor;
    AudioBottomPopWin<String> audioBottomPopWin;

    LiveMediaPlayBackInvoker liveMediaPlayBackInvoker;
    LivePlayBackUrlReciver livePlayBackUrlReciver;
    private TextView tvAnchorIcon;
    private View programListButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        vodRelevant.setVisibility(View.GONE);
        streamLineBtn.setVisibility(View.GONE);
        if (isFullScreen()) {
            ViewGroup.LayoutParams layoutParams = likeBadgeView.getLayoutParams();
            if (layoutParams instanceof ConstraintLayout.LayoutParams) {
                ConstraintLayout.LayoutParams cl = (ConstraintLayout.LayoutParams) layoutParams;
                cl.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
                likeBadgeView.setLayoutParams(cl);
            }
        }
        TaskAudioConfig config = APSHelper.getTaskConfig("" + articleItem.getId());
        if (config != null) {
            try {
                bitRateIndex = config.getBitRateIndex();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        streamLabelAdaptor = new AuidoStreamLineAdaptor(this, streamLabelList);
        audioBottomPopWin = new AudioBottomPopWin<String>(this);
        audioBottomPopWin.setItemClickListener(this);
        customViewLayout();
        initBroad();
        audioDetailCallBack = new AudioDetailCallBack();
        newsDetailInvoker = new NewsDetailInvoker(audioDetailCallBack);
        getAudioDetail();
        livePlayBackUrlReciver = new LivePlayBackUrlReciver();
        liveMediaPlayBackInvoker = new LiveMediaPlayBackInvoker(livePlayBackUrlReciver);
        onPageStart();
        //防止获取详情失败，提前着色
        tvAnchorIcon = mRootView.findViewById(R.id.tv_author_icon);
        if (tvAnchorIcon != null) {
            Drawable live_author_name_shape = ContextCompat.getDrawable(this, R.drawable.live_author_name_shape);
            live_author_name_shape = Utility.tintDrawable(DefaultBgUtil.getTintColor(this), live_author_name_shape);
            tvAnchorIcon.setBackground(live_author_name_shape);

            programListButton = mRootView.findViewById(R.id.programListButton);
            Drawable live_chat_list_shape = ContextCompat.getDrawable(this, R.drawable.live_chat_list_shape);
            live_chat_list_shape = Utility.tintDrawable(DefaultBgUtil.getTintColor(this), live_chat_list_shape);
            programListButton.setBackground(live_chat_list_shape);

            if (!TextUtils.isEmpty(articleItem.Author) && articleItem.Author.length() > 2) {
                tvAnchorIcon.setText(articleItem.Author.substring(articleItem.Author.length() - 2));
            } else {
                tvAnchorIcon.setText(articleItem.Author);
            }
        }
        TextView tvAnchorName = mRootView.findViewById(R.id.tv_anchor_name);
        tvAnchorName.setText(articleItem.Author);
        TextView textView = Utility.findViewById(mRootView, R.id.tv_live_statue);
        boolean replayFlag = getSharedPreferences(REPLAY_MARK_FLAG, Context.MODE_PRIVATE).getBoolean(REPLAY_MARK_FLAG + articleItem.getId(), false);
        if (textView != null) {
            if (!replayFlag)
                textView.setVisibility(View.GONE);
            else {
                textView.setVisibility(View.VISIBLE);
                if (chatRoomOpen) {
                    Drawable drawable = ContextCompat.getDrawable(AudioLiveDetailActivity.this, R.drawable.live_author_name_shape).mutate();
                    if (drawable instanceof GradientDrawable) {
                        ((GradientDrawable) drawable).setColor(DefaultBgUtil.getTintColor(this));
                    }
                    textView.setBackground(drawable);
                    textView.setText("回放");
                } else {
                    textView.setBackgroundColor(DefaultBgUtil.getTintColor(this));
                    textView.setText("回放");
                }
            }
        }
    }


    protected void customViewLayout() {
        loopModeBtn.setVisibility(View.GONE);
        next_audioBtn.setVisibility(View.GONE);
        prev_audioBtn.setVisibility(View.GONE);
    }


    class AuidoStreamLineAdaptor extends BaseAdaptor<String> {

        public AuidoStreamLineAdaptor(Context context, List<String> list) {
            super(context, list);
        }

        public AuidoStreamLineAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_audioline_item, null);
            }
            TextView audioLineItem = Utility.findViewById(convertView, R.id.audioLineItem);
            audioLineItem.setText(getItem(position));
            return convertView;
        }

    }

    @Override
    public void toggle() {
        apsKit.toggle();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AudioPlayer.getInstance().setVolumeListener(null);
    }

    private String chatId;
    public ChatLayout chatLayout;
    int lastInputLayoutHeight = 0;

    class AudioDetailCallBack implements DataInvokeCallBack<ArticleItemReciver> {
        @Override
        public void success(ArticleItemReciver data) {
            if (data.state) {

                if (data.chatRoom != null && data.chatRoom.isOpen && chatRoomOpen) {
                    if (!UserInfo.getUserInfo(AudioLiveDetailActivity.this).isLogin()) {
                        ToastUtil.show(AudioLiveDetailActivity.this, "请先进行登录");
                        finish();
                        return;
                    }
                    chatId = data.chatRoom.groupId;
                    TextView tvTitle = mRootView.findViewById(R.id.audioName);
                    tvTitle.setText(data.articleItem.getTitle());
                    chatLayout = findViewById(R.id.chat_layout);
                    chatLayout.initDefault();
                    TIMGroupManager.getInstance().applyJoinGroup(chatId, "some reason", new TIMCallBack() {
                        @java.lang.Override
                        public void onError(int code, String desc) {
                            //接口返回了错误码 code 和错误描述 desc，可用于原因
                            //错误码 code 列表请参见错误码表
                            Log.e(TAG, "applyJoinGroup err code = " + code + ", desc = " + desc);
                            if (code == 10013) {//被邀请加入的用户已经是群成员
                                initChatInfo();
                            } else {
                                TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("ALChatRoom", data.articleItem.getTitle());
                                param.setGroupId(chatId);
                                TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack<String>() {
                                    @Override
                                    public void onError(int i, String s) {
                                        Log.e(TAG, "创群 onError" + s);
                                    }

                                    @Override
                                    public void onSuccess(String s) {
                                        Log.e(TAG, "创群 onSuccess");
                                        initChatInfo();
                                    }
                                });
                            }
                        }

                        @java.lang.Override
                        public void onSuccess() {
                            Log.i(TAG, "applyJoinGroup success");
                            initChatInfo();
                        }
                    });

                    final InputLayout inputLayout = chatLayout.getInputLayout();
                    chatLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            chatLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            if (lastInputLayoutHeight <= 0) {
                                lastInputLayoutHeight = chatLayout.getMeasuredHeight();
                            }
                            View topAuthorLayout = findViewById(R.id.topAuthorLayout);
                            //聊天室的高度大于最开始的高度除2就显示上面的那个条条  这个证明键盘是没弹出来的 主要是修复 折中处理27387的bug华为mate20会有遮挡输入框 主要这个布局太复杂  sdk也不好改 将就了
                            if (chatLayout.getMeasuredHeight() > (lastInputLayoutHeight / 2)) {
                                topAuthorLayout.setVisibility(View.VISIBLE);
                            } else {
                                topAuthorLayout.setVisibility(View.GONE);
                            }

                        }
                    });
                    inputLayout.setBackgroundColor(Color.WHITE);
                    final ImageView imageView = inputLayout.findViewById(R.id.voice_input_switch);
                    imageView.setImageResource(R.drawable.send_image);
                    final View sendButtonView = inputLayout.findViewById(R.id.send_btn);


                    ViewGroup pa = (ViewGroup) sendButtonView.getParent();
                    pa.removeView(sendButtonView);
                   /* View chat_message_layout=inputLayout.findViewById(R.id.chat_message_layout);
                    if(chat_message_layout!=null)//加paddingTop 主要是那个主播名字悬浮在上面  然后加个paddtop  主要也是解决27387的bug改了下布局层级
                    {
                        chat_message_layout.setPadding(chat_message_layout.getPaddingLeft(),getResources().getDimensionPixelSize(R.dimen.dimen43),chat_message_layout.getPaddingRight(),chat_message_layout.getBottom());
                    }*/
                    EditText editText = inputLayout.findViewById(R.id.chat_message_input);
                    if (editText != null) {
                        editText.setInputType(InputType.TYPE_CLASS_TEXT);
                        editText.setImeActionLabel("发送", EditorInfo.IME_ACTION_SEND);
                        editText.setImeOptions(EditorInfo.IME_ACTION_SEND);
                    }
                    editText.setHint("说点什么吧...");
                    editText.setGravity(Gravity.CENTER_HORIZONTAL);
                    editText.setBackgroundResource(R.drawable.audio_chat_input_bg);
                    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                            if (null != keyEvent && KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()) {
                                switch (keyEvent.getAction()) {
                                    case KeyEvent.ACTION_UP:
                                        sendButtonView.performClick();
                                        hideKeyBroad();
                                        return true;
                                    default:
                                        return true;
                                }
                            }
                            return false;
                        }
                    });
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
//                                inputLayout.startSendPhoto();
                                Class c = inputLayout.getClass();
                                Field field = c.getDeclaredField("mInputMoreFragment");
                                field.setAccessible(true);
                                InputMoreFragment inputMoreFragment = (InputMoreFragment) field.get(inputLayout);
                                if (inputMoreFragment == null) {
                                    inputMoreFragment = new InputMoreFragment();
                                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().add(inputMoreFragment, "inputMoreFragment");
                                    fragmentTransaction.commit();
                                    field.set(inputLayout, inputMoreFragment);
                                }
                                Method method = c.getDeclaredMethod("startSendPhoto");
                                method.setAccessible(true);
                                method.invoke(inputLayout);
                            } catch (NoSuchMethodException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    final ImageView shareImage = inputLayout.findViewById(R.id.face_btn);
                    shareImage.setImageResource(R.drawable.chat_live_share_ico);
                    shareImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            moreClicked();
                        }
                    });
                    inputLayout.findViewById(R.id.chat_message_input).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            imageView.setImageResource(R.drawable.send_image);
                            shareImage.setImageResource(R.drawable.chat_live_share_ico);
                        }
                    });
                    mTitlebar_More.normalImg = ContextCompat.getDrawable(AudioLiveDetailActivity.this, R.drawable.appfactory_top_more_img);
                    mTitlebar_More.pressImg = ContextCompat.getDrawable(AudioLiveDetailActivity.this, R.drawable.appfactory_top_more_img);
                    mTitlebar_More.updateEffDrawable();
                    int color = Color.parseColor(getContent_show_top_color());
                    mTitlebar_More.setTint(color, color);
                }


                if (articleItem != null && articleItem.getFromComponent() != 1)
                    setNewsTitle();
                articleItem = data.articleItem;
                articleItem.setmShowSwitch(showSwitch);
                articleItem.chatRoomOpen = chatRoomOpen ? 1 : 0;
                openLikeBtn = articleItem != null && articleItem.getTagsflag() == 1 && AppFactoryGlobalConfig.getAppServerConfigInfo(AudioLiveDetailActivity.this).getOtherFunction() != null && AppFactoryGlobalConfig.getAppServerConfigInfo(AudioLiveDetailActivity.this).getOtherFunction().getSupport() > 0;// "1".equals(getResources().getString(R.string.openLikeBtn));
                if (openLikeBtn) {
                    likeBadgeView.setVisibility(View.VISIBLE);
                } else {
                    likeBadgeView.showBadgeText(false);
                    likeBadgeView.setVisibility(View.GONE);
                }
                UserRecommend.addItemKeyWord(articleItem, AudioLiveDetailActivity.this);

                //   badgeView.setText(articleItem.getCommentCount() + "");
                commentsBadgeView.setBadgeText(articleItem.getCommentCount() + "");
                if (articleItem.getCommentCount() > 0) {
                    commentsBadgeView.showBadgeText(true);
                } else {
                    commentsBadgeView.showBadgeText(false);
                    // FIXME: 2018/12/19 想办法优化小图标
                    commentsBadgeView.setBadgeTextViewGone();
                }
                setArgs();
                if (TextUtils.isEmpty(articleItem.getGoodsID())) {
                    normalPayUtil.showPaidView();
                    optUrl();
                } else {
                    normalPayUtil.judgeShowPayView(articleItem);
                }
                startAddIntegralCounter();
                AddMedalStatistics.addMedalStatistics(AudioLiveDetailActivity.this); //勋章统计
                // getComponentData();
            } else {
                ToastUtil.show(AudioLiveDetailActivity.this, R.string.noraml_newserror);
            }
            // broccoliLayout.setVisibility(View.GONE);
        }

        @Override
        public void fault(Object data) {
            //			mBaiduPlayer.setErrorViewVisible(View.VISIBLE);
            ToastUtil.show(AudioLiveDetailActivity.this, R.string.noraml_newserror);
        }
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(AudioLiveDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    private void initChatInfo() {
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.setId(chatId);
        chatInfo.setType(TIMConversationType.Group);
        getImUserInfo(chatInfo);
        chatLayout.setChatInfo(chatInfo);
        chatLayout.setBackgroundColor(0xFFF4F1F4);
        chatLayout.getTitleBar().setVisibility(View.GONE);
        chatLayout.getMessageLayout().setAvatarRadius(90);
    }

    private void getImUserInfo(ChatInfo chatInfo) {
        List<String> users = new ArrayList<String>();
        users.add(chatInfo.getId());
        UserInfo userInfo = UserInfo.getUserInfo(this);
        users.add(userInfo.getUser_chat_id());

        //获取用户资料
        TIMFriendshipManager.getInstance().getUsersProfile(users, true, new TIMValueCallBack<List<TIMUserProfile>>() {
            @Override
            public void onError(int code, String desc) {
                Log.w(TAG, "TIMFriendshipManager onError " + " " + code + " " + desc);
            }

            @Override
            public void onSuccess(List<TIMUserProfile> result) {
                Log.w(TAG, "TIMFriendshipManager onSuccess ");
            }
        });
    }

    @Override
    protected void onPaidAudio(String audio) {

        articleItem.setAudio(audio);
        optUrl();
    }

    protected void optUrl() {
        try {
            JSONObject video = new JSONObject(articleItem.getAudio());
            JSONArray tsAddress = video.optJSONArray("PC");
            cdnEncrypt = video.optString("cdnConfigEncrypt");
            bitRateTitles.clear();
            bitRateUrls.clear();
            for (int i = 0; i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                String title = line.optString("title");
                String url = line.optString("url");
                bitRateUrls.add(url);
                bitRateTitles.add(title);
            }

            if (bitRateIndex < bitRateUrls.size()) {
                MusicEntity entity = new MusicEntity(articleItem.getTitle(),bitRateUrls.get(bitRateIndex));
                entity.setAlbum("");
                entity.setSinger("");
                apsKit.setData(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show(this, R.string.noraml_newserror);
        }
    }

    @Override
    void openProgramList() {
        initAnimation();
        if (programListItems == null) {
            ToastUtil.showCustomView(this, R.string.isinvoke_audioprogramlist);
          /*  initProgramList();
            getProgramList();*/

            initProgramList();
            showOrHide();
        } else if (programListItems.size() == 0) {
            ToastUtil.showCustomView(this, R.string.no_audioprogramlist);
        } else {
            showOrHide();
        }
    }

    void initAnimation() {
        if (showAnimation != null)
            return;
       /* if(audioStyle!=AUDIO_STYLE_HALF_SCREEN)
        {*/
        //暂时这样吧  平移参数要研究一下
        showAnimation = AnimationUtils.loadAnimation(this, R.anim.show_audio_program_animation);
        /*    return;
        }
        AnimationSet animationSet=new AnimationSet(false);
        showAnimation = animationSet;//AnimationUtils.loadAnimation(this, R.anim.show_audio_program_animation);
        showAnimation.setDuration(300);
        TranslateAnimation translateAnimation=new TranslateAnimation(0,0,mRootView.getMeasuredHeight()-letmeSayLayout.getMeasuredHeight(),0);
        translateAnimation.setDuration(300);
        animationSet.getAnimations().add(translateAnimation);
        AlphaAnimation alphaAnimation=new AlphaAnimation(0,1);
        alphaAnimation.setDuration(300);
        animationSet.getAnimations().add(alphaAnimation);*/


    }

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-1, -1);

    void showOrHide() {
        if (audioStyle == AUDIO_STYLE_HALF_SCREEN)
            layoutParams.bottomMargin = letmeSayLayout.getMeasuredHeight();
        if (firstOpen) {
            ViewGroup parent = (ViewGroup) getWindow().getDecorView();
            if (programView.getParent() == null) {
                programView.setVisibility(View.GONE);
                parent.addView(programView, layoutParams);
            }
            firstOpen = false;
            Bundle bundle = new Bundle();
            bundle.putParcelable("data", articleItem);
            audioLiveProgramTable.setArguments(bundle);
            audioLiveProgramTable.setOnCloseBtnClickListenser(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    showAnimation.cancel();
                    ViewGroup parent = (ViewGroup) programView.getParent();
                    parent.removeView(programView);
                }
            });
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.audioLiveProgram, audioLiveProgramTable);
            transaction.show(audioLiveProgramTable);
            transaction.commitNowAllowingStateLoss();
            programView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showAnimation.cancel();
                    ViewGroup parent = (ViewGroup) programView.getParent();
                    parent.removeView(programView);
                }
            });
            getProgramList();
        } else {
            ViewGroup parentOld = (ViewGroup) programView.getParent();
            if (parentOld != null) parentOld.removeView(programView);
            programView.setVisibility(View.VISIBLE);
            ViewGroup parent = (ViewGroup) getWindow().getDecorView();
            if (programView.getParent() == null)
                parent.addView(programView, layoutParams);
            showAnimation.reset();
            programView.startAnimation(showAnimation);
        }
    }

    boolean firstOpen = true;

    protected void initProgramList() {
        if (programView == null) {
            programListItems = null;
            audioLiveProgramTable = new AudioLiveProgramTable();
            Bundle bundle = new Bundle();
            bundle.putBoolean("fullScreen", isFullScreen());
            audioLiveProgramTable.setArguments(bundle);
            programView = LayoutInflater.from(this).inflate(R.layout.aappfactory_audioliveprogram_popwin, null);
        }
    }

    protected void initBroad() {
        liveReplayBroadcast = new LiveReplayBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LiveReplayBroadcast.PlayAction);
        intentFilter.addAction(LiveReplayBroadcast.ToggleAction);
        liveReplayBroadcast.registed = true;
        LocalBroadcastManager.getInstance(this).registerReceiver(liveReplayBroadcast, intentFilter);
        liveReplayBroadcast.liveReplayHandle = this;
        liveReplayBroadcast.setToggleHandle(this);
    }

    @Override
    public void onBackPressed() {
        if (programView != null && programView.getParent() != null) {
            showAnimation.cancel();
            ViewGroup parent = (ViewGroup) programView.getParent();
            parent.removeView(programView);
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void initHalfScreenView() {
        if (isFullScreen()) {
            return;
        }
        super.initHalfScreenView();
        TextView textView = Utility.findViewById(mRootView, R.id.tv_live_statue);
        textView.setVisibility(View.GONE);
        currentPlayPosition.setVisibility(View.GONE);
        totoalLength.setVisibility(View.GONE);
    }

    @Override
    protected List<View> getPaidViews() {
        if (isFullScreen()) {
            return super.getPaidViews();
        }
        if (chatRoomOpen) {
            return super.getPaidViews();
        }
        List<View> list = new ArrayList<>();
        list.add(programBtn);
        return list;
    }

    @Override
    public void finish() {

        super.finish();
        if(apsKit.isPlaying()){
            if(apsKit.isTaskPlaying()){
                TaskAudioConfig config = new TaskAudioConfig(false, 0, bitRateIndex);
                APSHelper.saveTaskConfig("" + articleItem.getId(),config);
            }
            sendShowFloaWinMsg();
        }else{
            KillMusicUtils.hideReadNewsWin();
        }
        if (liveProgramListInvoker != null)
            liveProgramListInvoker.destory();
        liveProgramListInvoker = null;
        if (newsDetailInvoker != null)
            newsDetailInvoker.destory();
        newsDetailInvoker = null;
        if (liveReplayBroadcast != null && liveReplayBroadcast.registed) {
            liveReplayBroadcast.registed = false;
            LocalBroadcastManager.getInstance(this).unregisterReceiver(liveReplayBroadcast);
        }

    }

    protected void getAudioDetail() {
        if (isFinish)
            return;
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        newsDetailInvoker.getArticleById("" + articleItem.getId(), navigate_id);
    }

    protected void getProgramList() {
        if (programListCallBack == null) {
            programListCallBack = new ProgramListCallBack();
            liveProgramListInvoker = new VideoLiveProgramListInvoker(programListCallBack);
        }
        liveProgramListInvoker.getLiveVideoProgramList(articleItem);
    }

    class ProgramListCallBack implements DataInvokeCallBack<LiveProgramListReciver> {
        @Override
        public void success(LiveProgramListReciver data) {
            programListItems = data.programListItems;
            if (programListItems == null) {
                programListItems = new ArrayList<>();
            }
            if (programListItems.size() == 0) {
                ToastUtil.showCustomView(AudioLiveDetailActivity.this, R.string.no_audioprogramlist);
                return;
            }
            if (audioLiveProgramTable != null)
                audioLiveProgramTable.success(data);
            try {
                ProgramWeekItem programWeekItem = programListItems.get(audioLiveProgramTable.middle);
                if (programWeekItem != null && programWeekItem.programList != null) {
                    for (int idx = 0; idx < programWeekItem.programList.size(); idx++) {
                        ProgramListItem item = programWeekItem.programList.get(idx);
                        if (ProgramListItem.getItemState(item).equals(GuideItemState.LIVE)) {

                            String startTime = DateParse.getDate(0, 0, 0, 0, item.getStarttime(), null, "HH:mm");
                            String endTime = DateParse.getDate(0, 0, 0, 0, item.getEndtime(), null, "HH:mm");

                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            openProgramList();
        }

        @Override
        public void fault(Object data) {
            if (programListItems == null) {
                programListItems = new ArrayList<>();
            }
            Log.w(TAG, "get audio live programlist failed:" + data);
            openProgramList();
        }
    }

    @Override
    public void handleItem(ProgramListItem item) {

        try {

            if (GuideItemState.REPLAY == ProgramListItem.getItemState(item)) {
                //给他置个标记
                Date startDate = DateParse.parseDate(item.getStarttime(), null);
                Date endDate = DateParse.parseDate(item.getEndtime(), null);
                AuthMode mode = URLAuth.EncrptMode(cdnEncrypt, AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key, AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                startLong = startDate.getTime();
                endLong = endDate.getTime();
                liveMediaPlayBackInvoker.getLiveUrlPlayBackUrl(url, mode != null ? mode.getCode() : "", startLong, endLong);
            } else if (GuideItemState.LIVE == ProgramListItem.getItemState(item)) {
                startLong = 0L;
                endLong = 0L;
                apsKit.resetSourceAndPlayer();
                startPlay(url, articleItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void startPlay(String url, ArticleItem articleItem) {
        MusicEntity entity = new MusicEntity(articleItem.getTitle(),url);
        entity.setAlbum("");
        entity.setSinger("");
        apsKit.setData(entity);
    }



    @Override
    protected void showStreamLine() {
        audioBottomPopWin.setListAdaptor(streamLabelAdaptor);
        audioBottomPopWin.show(mRootView);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        position = position - audioBottomPopWin.audio_bottom_list.getHeaderViewsCount();
        String title = streamLabelList.get(position);
        //	streamLineBtn.setText(title);
        bitRateIndex = position;
        HashMap<String, Integer> value = new HashMap<String, Integer>();
        value.put(TAG, bitRateIndex);
        AppSharePreference.saveData(TAG, value, this);
        optUrl();

    }

    class LivePlayBackUrlReciver implements DataInvokeCallBack<BaseMessageReciver> {

        @Override
        public void success(BaseMessageReciver data) {
            Log.w(TAG, "LivePlayBackUrlReciver success");
            if (data.state) {
                JSONObject reciveData = data.orginData.optJSONObject("data");
                if (reciveData != null && !TextUtils.isEmpty(reciveData.optString(LiveMediaPlayBackInvoker.Url))) {
                    String url = reciveData.optString(LiveMediaPlayBackInvoker.Url);
                    apsKit.resetSourceAndPlayer();
                    startPlay(url, articleItem);
                } else {
                    ToastUtil.show(AudioLiveDetailActivity.this, R.string.getplaybackurlerror);
                }
            }
        }

        @Override
        public void fault(Object data) {
            Log.w(TAG, "LivePlayBackUrlReciver fault");
            ToastUtil.show(AudioLiveDetailActivity.this, R.string.getplaybackurlerror);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        SupportKit.INSTANCE.initSupportViewState(this, SupportKit.TYPE_1, "" + articleItem.getId(), likeBadgeView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {

            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }
    }
}